package com.spider.im.login.service;

import com.spider.im.chat.annotation.MessageTypeHandler;
import com.spider.im.chat.message.MessageStrategy;
import com.spider.im.chat.proto.ChatProto;
import com.spider.im.common.aspect.BusinessException;
import com.spider.im.login.annotation.LoginType;
import com.spider.im.login.enums.LoginTypeEnum;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
// 3. 创建上下文类来管理和调用相应的策略
@Component
public class LoginHandlerContext {

    private final Map<LoginTypeEnum, LoginService> loginMap = new ConcurrentHashMap<>();

    @Resource
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        // 获取所有实现了MessageStrategy接口的bean
        Map<String, Object> beansOfType = applicationContext.getBeansWithAnnotation(LoginType.class);
        for (Map.Entry<String, Object> entry : beansOfType.entrySet()) {
            Object bean = entry.getValue();
            if (bean instanceof LoginService) {
                LoginType annotation = bean.getClass().getAnnotation(LoginType.class);
                if (annotation != null) {
                    LoginTypeEnum type = annotation.type();
                    loginMap.put(type, (LoginService) bean);
                }
            }
        }
    }


    public LoginService getLoginService(LoginTypeEnum type) {
        LoginService loginService = (LoginService) loginMap.get(type);
        if (loginService != null) {
           return loginService;
        } else {
           log.error("No loginService found for type: {}", type);
           throw new BusinessException(500, "No loginService found for type: " + type);
        }
    }
}
